package org.springframework.beans.factory.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 默认实现的bean工厂
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {
    private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new BeansException("No bean named '" + beanName + "' is defined");
        }
        return beanDefinition;
    }


    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        Map<String, T> result = new HashMap<>();
        //通过bean定义对象里的class对象来判断类型是否是需要的
        beanDefinitionMap.forEach(((beanName, beanDefinition) -> {
            Class beanClass = beanDefinition.getBeanClass();
            if (type.isAssignableFrom(beanClass)) {
                //说明是符合类型的，要返回的bean对象
                T bean = (T) getBean(beanName);
                result.put(beanName, bean);
            }
        }));
        return result;
    }

    @Override
    public String[] getBeanDefinitionNames() {
        Set<String> beanNames = beanDefinitionMap.keySet();
        return beanNames.toArray(new String[beanNames.size()]);
    }

    @Override
    public void preInstantiateSingletons() throws BeansException {
        //提前实例化所有单例实例
        //其实就是全部都使用一次getBean方法 没有在单例池的就会自己创建到单例池了
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            //是单例bean才初始化时创建，getBean时就会创建不存在的bean
            //是单例的 并且不是懒加载的单例 才会直接初始化时创建
            if (beanDefinition.isSingleton() && !beanDefinition.isLazyInit()) {
                getBean(beanName);
            }
        });
    }

    /**
     * 根据类型查找bean
     *
     * @param requiredType
     * @param <T>
     * @return
     * @throws BeansException
     */
    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        //用来存放类型符合需要的bean的名字
        ArrayList<String> beanNames = new ArrayList<>();
        //遍历所有的bean定义对象 判断类型是否符合需要 符合则添加到集合里
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            Class beanClass = entry.getValue().getBeanClass();

            //当前bean定义对象的类型符合
            if (requiredType.isAssignableFrom(beanClass)) {
                beanNames.add(entry.getKey());
            }

        }

        //当集合里只有一个符合时 直接返回即可
        if (beanNames.size() == 1) {
            return getBean(beanNames.get(0), requiredType);
        }

        //当集合里的符合bean不止一个时 都要报错了
        throw new BeansException(requiredType + "expected single bean but found " +
                beanNames.size() + ": " + beanNames);
    }
}
